package com.xdq.serviceedu.config;

import com.xdq.serviceedu.utils.RequestAttributeContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!StringUtils.isEmpty(attributes)) {
            HttpServletRequest request = attributes.getRequest();
            requestTemplate.header("token", request.getHeader("token"));
        } else {
            RequestAttributes requestAttributes = RequestAttributeContext.getAttribute();
            if (null != requestAttributes) {
                RequestContextHolder.setRequestAttributes(requestAttributes);
            } else {
                System.out.println("requestAttributes is null");
            }

            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            if (!StringUtils.isEmpty(servletRequestAttributes)) {
                String token = servletRequestAttributes.getRequest().getHeader("token");
                requestTemplate.header("token",token);
            }
        }
    }
}
